package cool.taomu.box.kademlia.test

import com.dampcake.bencode.Bencode
import java.util.HashMap
import java.util.Map
import org.junit.Test
import java.io.FileInputStream
import com.dampcake.bencode.Type
import org.apache.commons.io.IOUtils
import java.util.Arrays

class BEncodeTest {
	@Test
	def void encodeTest() {
		var Bencode bencode = new Bencode();

		// 创建要编码的数据结构
		var Map<String, Object> dict = new HashMap();
		dict.put("announce", "192.168.1.220");
		dict.put("id", "1101010101010");
		dict.put("info", #{
			"length" -> 12345L,
			"name" -> "test.txt",
			"piece length" -> 262144L,
			"pieces" -> "binary hash data here".getBytes()
		});
		// 编码为 B 编码格式
		var byte[] encodedData = bencode.encode(dict);
		System.out.println(new String(encodedData));
	}

	@Test
	def void dencodeTest() {
		var Bencode bencode = new Bencode();
		
		// 从文件读取 B 编码数据
		var FileInputStream fis = new FileInputStream("./usecase/127.0.0.1.18080.local.torrent");
		var fisByte = IOUtils.toByteArray(fis)
		var Map<String, Object> decodedData = bencode.decode(fisByte, Type.DICTIONARY) as Map<String, Object>;
        println(decodedData.keySet)
        System.out.println("url-list: " + decodedData.get("url-list"));
        System.out.println("creation date: " + decodedData.get("creation date"));
        System.out.println("created by: " + decodedData.get("created by"));
        System.out.println("comment: " + decodedData.get("comment"));
		// 访问解码后的数据
		System.out.println("Announce URL: " + decodedData.get("announce"));

		var Map<String, Object> infoDict = decodedData.get("info") as Map<String, Object>;
		println(infoDict.keySet)
		System.out.println("Name: " + infoDict.get("name"));
		System.out.println("Length: " + infoDict.get("length"));
		System.out.println("Piece Length: " + infoDict.get("piece length"));
		
		System.out.println("Pieces: " + infoDict.get("pieces").class.name);
		// 获取 pieces 字段
		var byte[] pieces = (infoDict.get("pieces") as String).bytes;

		// 每个哈希值长度为20字节
		val int HASH_LENGTH = 20;
		for (var int i = 0; i < pieces.length && i + HASH_LENGTH < pieces.length; i += HASH_LENGTH) {
			if (i + HASH_LENGTH > pieces.length) {
				throw new IllegalArgumentException("Invalid piece hash length.");
			}
			// 提取单个哈希值
			var byte[] pieceHash = Arrays.copyOfRange(pieces, i, i + HASH_LENGTH);

			// 将哈希值转换为可读格式（例如十六进制）
			var String pieceHashHex = BEncodeUtils.bytesToHex(pieceHash);
			System.out.println("Piece Hash " + (i / HASH_LENGTH) + ": " + pieceHashHex);
		}

	}

}
